import { createSlice, PayloadAction, createAsyncThunk } from '@reduxjs/toolkit';
import { logout as logoutApi } from '../../services/auth';

// 异步登出 thunk
export const logoutAsync = createAsyncThunk(
  'auth/logoutAsync',
  async (_, { rejectWithValue }) => {
    try {
      const response = await logoutApi();
      if (response.code === 0) {
        return response.data;
      } else {
        return rejectWithValue(response.msg);
      }
    } catch (error) {
      return rejectWithValue('登出失败');
    }
  }
);

interface AuthState {
  token: string | null;
  user: any | null;
  isLoggedIn: boolean;
}

const initialState: AuthState = {
  token: localStorage.getItem('token'),
  user: null,
  isLoggedIn: !!localStorage.getItem('token'),
};

const authSlice = createSlice({
  name: 'auth',
  initialState,
  reducers: {
    setToken: (state, action: PayloadAction<string>) => {
      state.token = action.payload;
      state.isLoggedIn = true;
      localStorage.setItem('token', action.payload);
    },
    setUser: (state, action: PayloadAction<any>) => {
      state.user = action.payload;
    },
    logout: (state) => {
      state.token = null;
      state.user = null;
      state.isLoggedIn = false;
      localStorage.removeItem('token');
      localStorage.removeItem('menuData');
    },
  },
  extraReducers: (builder) => {
    builder.addCase(logoutAsync.fulfilled, (state) => {
      state.token = null;
      state.user = null;
      state.isLoggedIn = false;
      localStorage.removeItem('token');
      localStorage.removeItem('menuData');
    });
  },
});

export const { setToken, setUser, logout } = authSlice.actions;
export default authSlice.reducer;